package com.hex.ds.hdrs.engine.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.hex.ds.hdrs.center.service.CenterManager;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.constant.ErrorCode;
import com.hex.ds.hdrs.common.exception.BizException;
import com.hex.ds.hdrs.common.helper.ListHelper;
import com.hex.ds.hdrs.common.utils.HdrsDateUtil;
import com.hex.ds.hdrs.common.utils.ListUtil;
import com.hex.ds.hdrs.engine.manager.LstFinishManager;
import com.hex.ds.hdrs.engine.manager.RunningManager;
import com.hex.ds.hdrs.engine.manager.ToDoManager;
import com.hex.ds.hdrs.engine.manager.ToRunManager;
import com.hex.ds.hdrs.period.job.po.JobTask;
import com.hex.ds.hdrs.period.job.po.PeriodJob;
import com.hex.ds.hdrs.period.job.service.PeriodJobService;
import com.hex.ds.hdrs.period.task.po.PeriodTask;
import com.hex.ds.hdrs.period.task.po.TaskTrack;
import com.hex.ds.hdrs.period.task.service.PeriodTaskService;
import com.hex.ds.hdrs.period.task.service.TaskService;
import com.hex.ds.hdrs.period.task.util.TaskTrackHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.hex.ds.hdrs.engine.service
 * @ClassName LoaderService
 * @Description: 加载器
 * @Author: jd.chen
 * @Date 2021/7/5 18:45
 * @Version v1.0
 **/
@Slf4j
@Service
public class LoaderService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private CenterManager centerManager;
    @Autowired
    private ToDoManager toDoManager;
    @Autowired
    private ToRunManager toRunManager;
    @Autowired
    private RunningManager runningManager;
    @Autowired
    private LstFinishManager lstFinishManager;
    @Autowired
    private PeriodJobService periodJobService;
    @Autowired
    private PeriodTaskService periodTaskService;

    /**
     * 初始化
     */
    public void init() {
        log.debug("加载器--初始化【LoaderService.init】开始=======》");
        if (!centerManager.isCanDeal()) {
            log.warn("【该中心不是Master】======");
            return;
        }
        try {
            // 1. 打标
            toDoManager.setMark(Const.INIT_LOADER_MARK);
            // 2. toDo查询DB  初始化
            this.initJobTaskList();
        } catch (Exception e) {
            log.error("加载器--初始化【LoaderService.init】异常:{}", e.getMessage());
            // 初始化失败，清空内存
            toDoManager.clear();
            throw new BizException(ErrorCode.ERROR_810004);
        } finally {
            log.debug("加载器--初始化【LoaderService.init】结束《=======");
            toDoManager.setMark(Const.FREE_LOADER_MARK);
        }
    }

    /**
     * 获取全量 JobTaskList
     *
     * @return
     */
    public List<JobTask> getAllJobTaskList() {
        log.debug("全量--获取jobTaskList【LoaderService.getAllJobTaskList】=======》");
        //1. 设置本次查询时间
        toDoManager.setCurQryTs(DateUtil.now());
        //2. 获取jobList
        List<PeriodJob> jobList = this.taskService.qryJobList();
        //3. 获取toDotaskList
        List<PeriodTask> toDoTaskList = this.taskService.qryToDoTaskList();
        //4. 给任务添加轨迹
        this.addSuccTaskTrack(toDoTaskList, Const.TRACK_TYPE_ALL_TO_DO);
        //5. 合并得到jobTaskList
        return this.getJobTaskList(jobList, toDoTaskList);
    }

    /**
     * 初始化 JobTaskList
     *
     * @return
     */
    public void initJobTaskList() {
        log.debug("初始化 JobTaskList【LoaderService.initJobTaskList】=======》");
        //1. 设置本次查询时间
        toDoManager.setCurQryTs(DateUtil.now());
        //2. 获取jobList
        List<PeriodJob> jobList = this.taskService.qryJobList();
        //3. 获取taskList
        List<PeriodTask> taskList = this.taskService.qryToDoTaskList();
        //4. 给任务添加轨迹
        this.addSuccTaskTrack(taskList, Const.TRACK_TYPE_INIT_TO_DO);
        //5. 初始化toDo  running
        this.initToDoAndRunning(jobList, taskList);
    }

    /**
     * 初始化todo running
     *
     * @param jobList
     * @param taskList
     */
    public void initToDoAndRunning(List<PeriodJob> jobList, List<PeriodTask> taskList) {
        log.info("初始化todo running【LoaderService.initRunningList】=======》");
        List<PeriodTask> toDoTaskList = new ArrayList<>();
        List<PeriodTask> runningTaskList = new ArrayList<>();
        for (PeriodTask task : taskList) {
            if (Const.TASK_TODO_RUN.equals(task.getTaskStatus())) {
                toDoTaskList.add(task);
            } else if (Const.TASK_RUNNING.equals(task.getTaskStatus())) {
                runningTaskList.add(task);
            }
        }

        List<PeriodJob> toDoJobList = new ArrayList<>();
        List<PeriodJob> runningJobList = new ArrayList<>();
        Map<String, List<PeriodTask>> runningListMap = ListHelper.taskListToMap(runningTaskList);
        for (PeriodJob job : jobList) {
            if (runningListMap.containsKey(job.getJobCode())) {
                runningJobList.add(job);
            } else {
                toDoJobList.add(job);
            }
        }

        //1. 初始化running
        //this.initRunningList(runningJobList, runningTaskList);
        this.initRunningTask2ToDo(runningTaskList);
        //2. 初始化toDo
        this.initToDoList(toDoJobList, toDoTaskList);
    }

    /**
     * @Method initRunningTak2ToDo <br>
     * @Param
     * @Param runningTaskList <br>
     * @Return void <br>
     * @Description 初始化将执行中任务置为待处理<br>
     * @Author jian.qiao<br>
     * @Date 2024/2/6 17:52 <br>
     * @Version V1.0<br>
     */
    public void initRunningTask2ToDo(List<PeriodTask> runningTaskList){
        for (PeriodTask task : runningTaskList) {
            periodTaskService.upTaskToDo(task.getPkId(), HdrsDateUtil.getCurTs());
        }
    }

    /**
     * 初始化runningTaskList
     *
     * @param jobList
     * @param taskList
     */
    public void initRunningList(List<PeriodJob> jobList, List<PeriodTask> taskList) {
        List<JobTask> jobTaskList = this.getJobTaskList(jobList, taskList);
        Map<String, JobTask> jobTaskMap = ListHelper.jobTaskListToMap(jobTaskList);
        Map<String, PeriodTask> taskMap = ListHelper.taskListToTaskMap(taskList);
        runningManager.init(jobTaskList, jobTaskMap, taskList, taskMap);
    }

    /**
     * 初始化toDoTaskList
     *
     * @param jobList
     * @param taskList
     */
    public void initToDoList(List<PeriodJob> jobList, List<PeriodTask> taskList) {
        List<JobTask> jobTaskList = this.getJobTaskList(jobList, taskList);
        toDoManager.init(jobTaskList);
    }

    /**
     * 添加加载成功的任务轨迹
     *
     * @param taskList
     */
    public void addSuccTaskTrack(List<PeriodTask> taskList, String type) {
        TaskTrack taskTrack = TaskTrackHelper.loadSucc(type);
        for (PeriodTask task : taskList) {
            if (StrUtil.equalsAnyIgnoreCase(task.getTaskStatus(), Const.TASK_TODO_RUN)) {
                log.debug("【任务添加运行轨迹】任务实例编码：{}，业务日期：{},添加任务轨迹类型：{}", task.getTaskCode(), task.getBizDate(), type);
                TaskTrackHelper.addTaskTrack(task, taskTrack);
            }
        }
    }

    /**
     * 获取增量 JobTaskList
     *
     * @return
     */
    public List<JobTask> getAddJobTaskList() {
        //1. 设置本次查询时间
        toDoManager.setCurQryTs(DateUtil.now());
        //2. 获取jobList
        List<PeriodJob> jobList = this.taskService.qryJobList(toDoManager.getLastQryTs());
        //3. 获取taskList
        List<PeriodTask> taskList = this.taskService.qryToDoTaskList(toDoManager.getLastQryTs());
        //4. 添加加载成功的任务轨迹
        this.addSuccTaskTrack(taskList, Const.TRACK_TYPE_ADD_TO_DO);
        //5. 合并得到jobTaskList
        return this.getJobTaskList(jobList, taskList);
    }

    /**
     * 全量--合并分发队列
     *
     * @param jobTaskList 待处理作业队列
     * @return
     */
    public List<JobTask> mergeDispenseList(List<JobTask> jobTaskList) {
        log.debug("【LoaderExec.allDeal】全量合并分发队列--开始");
        List<JobTask> newJobTaskList = new ArrayList<>(jobTaskList.size());
        for (JobTask jobTask : jobTaskList) {
            if (mergeDispenseJobTask(jobTask)) {
                newJobTaskList.add(jobTask);
            }
        }
        log.debug("【LoaderExec.allDeal】全量合并分发队列--结束");
        return newJobTaskList;
    }

    /**
     * 增量--合并分发队列
     *
     * @param jobTaskList 待处理作业队列
     * @return
     */
    public List<JobTask> mergeAddDispenseList(List<JobTask> jobTaskList) {
        log.debug("【LoaderExec.addExec】更新分发队列--开始");
        List<JobTask> newJobTaskList = new ArrayList<>(jobTaskList.size());
        for (JobTask jobTask : jobTaskList) {
            log.debug("【LoaderExec.addExec】增量作业实例编码:{}, 业务日期:{}", jobTask.getJobCode(), jobTask.getBizDate());
            if (mergeAddDispenseJobTask(jobTask)) {
                newJobTaskList.add(jobTask);
            }
        }
        log.debug("【LoaderExec.addExec】更新分发队列--结束【{}】", newJobTaskList.size());
        return newJobTaskList;
    }


    /**
     * 增量--合并增量待处理队列
     *
     * @param srcJobTaskList
     */
    public void mergeAddToDo(List<JobTask> srcJobTaskList) {
        log.debug("【LoaderExec.addExec】更新待处理队列--开始,处理任务个数：{}", srcJobTaskList.size());
        List<JobTask> appDeltaList = toDoManager.getDeltaAppJobList();
        Map<String, JobTask> appDeltaMap = ListHelper.jobTaskListToMap(appDeltaList);

        for (JobTask srcJobTask : srcJobTaskList) {
            if (!toDoManager.isContainsJob(srcJobTask.getJobCode())) {
                //job在Delta中存在 且job已完成  则不添加
                if (this.jobFinishInDelta(srcJobTask, appDeltaMap)) {
                    log.debug("【LoaderExec.addExec】作业编码:{}在Delta中存在 且job已完成", srcJobTask.getJobCode());
                    continue;
                }
                // 待执行队列不存在的 job在Delta  作业 添到待执行队列中
                toDoManager.addJob(srcJobTask, Const.TRACK_TYPE_DELTA_TO_DO);
            } else {
                JobTask job = toDoManager.getJob(srcJobTask.getJobCode());
                String jobCode = job.getJobCode();
                String toDoBizDate = job.getBizDate();
                String dbBizDate = srcJobTask.getBizDate();

                if (toDoBizDate.equals(dbBizDate)) {
                    this.mergeJobTask(srcJobTask, job, Const.JOB_IN_TO_DO);
                } else if (DateUtil.parse(toDoBizDate).after(DateUtil.parse(dbBizDate))) {
                    log.warn("【LoaderExec.addExec】增量加载，作业实例：{}，DB中的业务日期：{}【小于】内存待处理队列中作业的业务日期：{}", jobCode, dbBizDate, toDoBizDate);
                    toDoManager.removeJob(job);
                    toDoManager.addJob(srcJobTask, Const.TRACK_TYPE_DELTA_TO_DO);
                } else {
                    log.warn("【LoaderExec.addExec】增量加载，作业实例：{}，DB中的业务日期：{}【大于】内存待处理队列中作业的业务日期：{}", jobCode, dbBizDate, toDoBizDate);
                    continue;
                }
            }
        }
        log.debug("【LoaderExec.addExec】更新待处理队列--结束");
    }


    /**
     * 合并 delta 到待执行队列
     */
    public void mergeDeltaToDo() {
        log.debug("【LoaderExec.allDeal】合并 delta 到待执行队列!");
        List<PeriodJob> lstFinishList = lstFinishManager.getDeltaJobList();
        for (PeriodJob deltaJob : lstFinishList) {
            log.debug("【LoaderExec.allDeal】移除已经完成的作业:{}, 业务日期: {}", deltaJob.getJobCode(), deltaJob.getBizDate());
            if (toDoManager.isContainsJob(deltaJob.getJobCode())) {
                JobTask jobTask = toDoManager.getJob(deltaJob.getJobCode());
                if (jobTask.getBizDate().equals(deltaJob.getBizDate())) {
                    toDoManager.removeJob(jobTask);
                    continue;
                }
            }
        }

        List<JobTask> deltaJobTaskList = toDoManager.getDeltaAppJobList();
        log.debug("【LoaderExec.allDeal】合并 delta 到待执行队列, 个数:{}", deltaJobTaskList.size());
        if (!ListUtil.isEmpty(deltaJobTaskList)) {
            for (JobTask deltaJobTask : deltaJobTaskList) {
                if (!toDoManager.isContainsJob(deltaJobTask.getJobCode())) {
                    log.debug("【LoaderExec.allDeal】dtlta 中任务添加到待处理队列，任务:{}, 业务日期: {}", deltaJobTask.getJobCode(), deltaJobTask.getBizDate());
                    toDoManager.addToDoJob(deltaJobTask, Const.TRACK_TYPE_DELTA_TO_DO);
                } else {
                    JobTask job = toDoManager.getJob(deltaJobTask.getJobCode());
                    String toDoBizDate = job.getBizDate();
                    String deltaBizDate = deltaJobTask.getBizDate();
                    if (StrUtil.equalsAnyIgnoreCase(toDoBizDate, deltaBizDate)) {
                        log.debug("【LoaderExec.allDeal】dtlta 中任务合并到待处理队列，任务:{}, 业务日期: {}", deltaJobTask.getJobCode(), deltaJobTask.getBizDate());
                        this.mergeJobTask(deltaJobTask, job, Const.JOB_IN_TO_DO);
                    } else {
                        log.warn("【LoaderExec.allDeal】合并 delta 到待执行队列, delta中作业：{}业务日期：{}【不等于】内存中作业业务日期{}: ", job.getJobCode(), deltaBizDate, toDoBizDate);
                        continue;
                    }
                }
            }
        }
    }


    /**
     * 全量分发队列
     *
     * @param srcJobTask
     * @return
     */
    private boolean mergeDispenseJobTask(JobTask srcJobTask) {
        log.debug("【LoaderExec.allDeal】全量合并分发队列，作业编码:{},业务日期:{},", srcJobTask.getJobCode(), srcJobTask.getBizDate());
        String jobCode = srcJobTask.getJobCode();
        String bizDate = srcJobTask.getBizDate();

        if (runningManager.isContainsJob(jobCode)) {
            JobTask job = runningManager.getJob(jobCode);
            if (job.getBizDate().equals(bizDate)) {
                log.debug("【LoaderExec.allDeal】全量合并分发队列，作业编码:{},业务日期:{},作业在【正在运行队列】中并且业务日期相等！", job.getJobCode(), job.getBizDate());
                this.mergeJobTask(srcJobTask, job, Const.JOB_IN_RUNNING);
                return false;
            } else {
                log.warn("【LoaderExec.allDeal】全量合并分发队列，作业编码:{},DB业务日期:{}, 内存业务日期:{},在正在运行队列中但业务日期不相等！", jobCode, srcJobTask.getBizDate(), job.getBizDate());
                return false;
            }
        } else {
            // 判断作业状态,作业状态为完成则不在添加待处理队列，避免出现并发问题导致任务重跑
            PeriodJob periodJob = periodJobService.queryByJobCodeAndBizDate(jobCode,bizDate);
            if (StrUtil.equalsAnyIgnoreCase(periodJob.getJobStatus(), Const.JOB_DO_SUCCESS)){
                return false;
            }
        }

        if (toRunManager.isContainsJob(jobCode)) {
            JobTask job = toRunManager.getJob(jobCode);
            if (job.getBizDate().equals(bizDate)) {
                log.debug("【LoaderExec.allDeal】全量合并分发队列，作业编码:{},业务日期:{},作业在【可执行队列】中并且业务日期相等！", job.getJobCode(), job.getBizDate());
                this.mergeJobTask(srcJobTask, job, Const.JOB_IN_TO_RUN);
                return false;
            } else if (DateUtil.parse(job.getBizDate()).after(DateUtil.parse(bizDate))) {
                log.warn("【LoaderExec.allDeal】全量合并分发队列，作业编码:{},DB业务日期:{},内存业务日期:{},作业在【可执行队列】中但内存中业务日期【大于】DB中的业务日期！", job.getJobCode(), srcJobTask.getBizDate(), job.getBizDate());
                toRunManager.removeJob(job.getCurTask(), "Load_BizDate_Min");
                return true;
            } else {
                log.warn("【LoaderExec.allDeal】全量合并分发队列，作业编码:{},DB业务日期:{},内存业务日期:{},作业在【可执行队列】中但内存中业务日期【小于】DB中的业务日期！", job.getJobCode(), srcJobTask.getBizDate(), job.getBizDate());
                PeriodJob periodJob = periodJobService.queryByJobCodeAndBizDate(job.getJobCode(), job.getBizDate());
                if (periodJob != null && !Const.PERIOD_JOB_STATUS_SUCCESS.equals(periodJob.getJobStatus())) {
                    log.warn("【LoaderExec.allDeal】全量合并分发队列，作业编码: {},在内存中作业业务日期: {}【小于】DB中的业务日期: {}", srcJobTask.getJobCode(), job.getBizDate(), srcJobTask.getBizDate());
                    return false;
                } else {
                    log.warn("【LoaderExec.allDeal】全量合并分发队列，作业编码: {},在内存中作业业务日期: {}【小于】DB中的业务日期: {}，且内存中的作业实例在数据库中已不存在或已完成！", srcJobTask.getJobCode(), job.getBizDate(), srcJobTask.getBizDate());
                    toRunManager.removeJob(job.getCurTask(), "Load_BizDate_Min");
                    return true;
                }
            }
        } else {
            clearToRunPeriodJobByJobCode(jobCode);
        }
        return true;
    }

    /**
     * 增量分发队列
     * 在分发队列做过更新的返回null
     *
     * @param srcJobTask
     * @return
     */
    private boolean mergeAddDispenseJobTask(JobTask srcJobTask) {
        if (runningManager.isContainsJob(srcJobTask.getJobCode())) {
            JobTask job = runningManager.getJob(srcJobTask.getJobCode());
            if (job.getBizDate().equals(srcJobTask.getBizDate())) {
                log.debug("【LoaderExec.addDeal】增量合并分发队列，作业编码:{},业务日期:{},作业在【正在运行队列】中并且业务日期相等！", job.getJobCode(), job.getBizDate());
                this.mergeJobTask(srcJobTask, job, Const.JOB_IN_RUNNING);
            } else {
                log.info("【LoaderExec.addDeal】增量合并分发队列，作业编码:{},DB业务日期:{}, 内存业务日期:{},在正在运行队列中但业务日期不相等！", job.getJobCode(), srcJobTask.getBizDate(), job.getBizDate());
            }
            return false;
        }

        if (!toRunManager.isContainsJob(srcJobTask.getJobCode())) {
            clearToRunPeriodJobByJobCode(srcJobTask.getJobCode());
            return true;
        }
        JobTask job = toRunManager.getJob(srcJobTask.getJobCode());
        if (job.getBizDate().equals(srcJobTask.getBizDate())) {
            this.mergeJobTask(srcJobTask, job, Const.JOB_IN_TO_RUN);
            return false;
        } else if (DateUtil.parse(job.getBizDate()).after(DateUtil.parse(srcJobTask.getBizDate()))) {
            log.warn("【LoaderExec.addExec】可执行队列信息同步，作业编码: {},在内存中作业业务日期: {}【大于】DB中的业务日期: {}", srcJobTask.getJobCode(), job.getBizDate(), srcJobTask.getBizDate());
            toRunManager.removeJob(job.getCurTask(), "Load_BizDate_Min");
            return true;
        } else {
            PeriodJob periodJob = periodJobService.queryByJobCodeAndBizDate(job.getJobCode(), job.getBizDate());
            if (periodJob != null && !Const.PERIOD_JOB_STATUS_SUCCESS.equals(periodJob.getJobStatus())) {
                log.warn("【LoaderExec.addExec】可执行队列信息同步，作业编码: {},在内存中作业业务日期: {}【小于】DB中的业务日期: {}", srcJobTask.getJobCode(), job.getBizDate(), srcJobTask.getBizDate());
                return false;
            } else {
                log.warn("【LoaderExec.addExec】可执行队列信息同步，作业编码: {},在内存中作业业务日期: {}【小于】DB中的业务日期: {}，且内存中的作业实例在数据库中已不存在或已完成！", srcJobTask.getJobCode(), job.getBizDate(), srcJobTask.getBizDate());
                toRunManager.removeJob(job.getCurTask(), "Load_BizDate_Min");
                return true;
            }
        }
    }

    /*
     * @Method: clearToRunPeriodJobByJobCode <br>
     * @Param: [jobCode] <br>
     * @Return: void <br>
     * @Description：清除可执行队列中冗余数据<br>
     * @Author： wz.li<br>
     * @Date： 2022/12/11 17:24 <br>
     * @Version： V2.0.2<br>
     */
    private void clearToRunPeriodJobByJobCode(String jobCode) {
        if (toRunManager.getJob(jobCode) != null) {
            JobTask jobTask = toRunManager.getJob(jobCode);
            for (PeriodTask periodTask : jobTask.getPeriodTasks()) {
                toRunManager.removeJob(periodTask, "手动移除");
            }
        }
    }

    /**
     * 比较并更新作业任务队列
     *
     * @param srcJob
     * @param targetJob
     * @return
     */
    private void mergeJobTask(JobTask srcJob, JobTask targetJob, String mergeType) {
        log.debug("比较并更新作业任务队列【LoaderService.mergeJobTask】===》DBJob【{}】【{}】、内存Job【{}】【{}】", srcJob.getJobCode(), srcJob.getBizDate(), targetJob.getJobCode(), targetJob.getBizDate());
        boolean isHasUp = false;

        //1. 比较作业是否需要更新
        this.mergeJob(srcJob, targetJob);

        //2. 比较任务是否需要更新
        List<PeriodTask> srcTaskList = srcJob.getPeriodTasks();
        PeriodTask curTask = targetJob.getCurTask();
        if (curTask == null) {
            log.warn("当前任务为空【jobTask.getCurTask】job: {} bizDate: {}", targetJob.getJobCode(), targetJob.getBizDate());
            return;
        } else {
            for (PeriodTask srcTask : srcTaskList) {
                PeriodTask targetTask = targetJob.getTask(srcTask.getTaskCode());
                if (targetTask == null) {
                    log.error("目标作业中不存在该源任务【LoaderService.mergeJobTask】,任务编号: {} 目标作业编号: {}", srcTask.getTaskCode(), targetJob.getJobCode());
                } else if (targetTask.getTaskCode().equals(curTask.getTaskCode())) {
                    //当前任务合并处理
                    isHasUp = this.mergeCurTask(srcTask, targetJob, mergeType);
                } else {
                    this.mergeTask(srcTask, targetJob);
                }
            }

            //3. 添加到todolist
            if (Const.JOB_IN_TO_RUN.equalsIgnoreCase(mergeType) && isHasUp) {
                toRunManager.toRunToToDo(curTask, Const.TRACK_TYPE_RUN_TO_DO, toDoManager);
            }
        }
    }

    /**
     * 合并内存中当前任务的处理
     *
     * @param srcTask
     * @param targetJob
     * @param mergeType
     * @return
     */
    private boolean mergeCurTask(PeriodTask srcTask, JobTask targetJob, String mergeType) {
        log.info("合并内存中当前任务的处理【LoaderService.mergeCurTask】=======》");
        if (Const.JOB_IN_RUNNING.equalsIgnoreCase(mergeType)) {
            log.error("正在运行中的任务不处理【LoaderService.mergeCurTask】,任务编号: {} 目标作业编号: {}", srcTask.getTaskCode(), targetJob.getJobCode());
            return false;
        } else if (Const.JOB_IN_TO_RUN.equalsIgnoreCase(mergeType)) {
            log.info("处于可执行的任务处理【LoaderService.mergeCurTask】,任务编号: {} 目标作业编号: {}", srcTask.getTaskCode(), targetJob.getJobCode());
            return this.mergeTask(srcTask, targetJob);
        } else {
            this.mergeTask(srcTask, targetJob);
        }
        return false;
    }

    /**
     * 合并作业状态、时间
     *
     * @param srcJob
     * @param targetJob
     * @return
     */
    private boolean mergeJob(JobTask srcJob, JobTask targetJob) {
        log.debug("合并作业状态、时间【mergeJob】===》srcJob【{}】【{}】targetJob【{}】【{}】", srcJob.getJobCode(), srcJob.getBizDate(), targetJob.getJobCode(), targetJob.getBizDate());
        if (DateUtil.parse(srcJob.getUpTs()).after(DateUtil.parse(targetJob.getUpTs()))) {
            targetJob.updateJobStatus(srcJob.getUpTs(), srcJob.getJobStatus());
            return true;
        }
        return false;
    }

    /**
     * 合并任务状态、时间
     *
     * @param srcTask
     * @param targetJob
     * @return
     */
    private boolean mergeTask(PeriodTask srcTask, JobTask targetJob) {
        PeriodTask targetTask = targetJob.getTask(srcTask.getTaskCode());
        if (targetTask != null) {
            log.info("合并任务状态、时间【mergeTask】===》srcJob【{}】【{}】targetJob【{}】【{}】", srcTask.getTaskCode(), srcTask.getBizDate(), targetTask.getTaskCode(), targetTask.getBizDate());
            //合并任务
            if (DateUtil.parse(srcTask.getUpTs()).after(DateUtil.parse(targetTask.getUpTs()))) {
                targetJob.updateTaskStatus(srcTask.getTaskCode(), targetTask.getUpTs(), srcTask.getTaskStatus());
                return true;
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * 得到作业任务列表
     *
     * @param jobList
     * @param taskList
     * @return
     */
    private List<JobTask> getJobTaskList(List<PeriodJob> jobList, List<PeriodTask> taskList) {
        List<JobTask> jobTaskList = new ArrayList<>();
        Map<String, List<PeriodTask>> taskListMap = ListHelper.taskListToMap(taskList);
        for (PeriodJob job : jobList) {
            log.debug("【合并组合作业实例JobTask对象】作业编码:{}, 业务日期:{}", job.getJobCode(), job.getBizDate());
            String jobCode = job.getJobCode();
            if (!taskListMap.containsKey(jobCode)) {
                log.warn("【合并组合作业实例JobTask对象】作业实例存在，但任务实例不存在，作业编码:{}, 业务日期:{}", job.getJobCode(), job.getBizDate());
                continue;
            }

            List<PeriodTask> periodTaskList = taskListMap.get(jobCode);
            String jobBizDate = job.getBizDate();
            String taskBizDate = periodTaskList.get(0).getBizDate();
            if (!jobBizDate.equals(taskBizDate)) {
                log.warn("【合并组合作业实例JobTask对象】作业实例和任务实例业务日期异常,作业编码:{}, 业务日期:{},任务业务日期:{}", jobCode, jobBizDate, taskBizDate);
                continue;
            }

            JobTask jobTask = new JobTask(job, periodTaskList);
            jobTaskList.add(jobTask);
        }
        return jobTaskList;
    }

    /**
     * job在Delta中存在 且job已完成  则不添加
     *
     * @param srcJobTask
     * @return
     */
    private boolean jobFinishInDelta(JobTask srcJobTask, Map<String, JobTask> jobTaskMap) {
        log.debug("增量--合并待处理队列【LoaderService.jobFinishInDelta】=======》");
        String srcJobCode = srcJobTask.getJobCode();
        if (jobTaskMap.containsKey(srcJobCode) && jobTaskMap.get(srcJobCode).isFinish()) {
            return true;
        }
        return false;
    }
}
